Wang Haihua
🍈 🍉🍊 🍋 🍌
考虑这个问题:已知点$(1,3)$,$(2, -2)$ ,$(3, -5)$, and $(4, 0)$,如何找到一个经过这些点的三次多项式?
三次多项式的形式为
\begin{align} y=a_0+a_1x+a_2x^2+a_3x^3 \end{align}我们将点代入
\begin{align} (x,y)&=(1,3)\qquad\longrightarrow\qquad \ 2=a_0+3a_1+9a_2 +27a_3 \\ (x,y)&=(2,-2)\qquad\longrightarrow\qquad 3=a_0+a_1+a_2+a_3\\ (x,y)&=(3,-5)\qquad\longrightarrow\qquad 2=a_0-4a_1+16a_2-64a_3\\ (x,y)&=(4,0)\qquad\longrightarrow\qquad -2=a_0+2a_1+4a_2+8a_3 \end{align}增广矩阵是 $$ \left[\begin{matrix}1 & 1 & 1 & 1 & 3\\1 & 2 & 4 & 8 & -2\\1 & 3 & 9 & 27 & -5\\1 & 4 & 16 & 64 & 0\end{matrix}\right] $$
解得最简阶梯形矩阵为
$$ \left[\begin{matrix}1 & 0 & 0 & 0 & 4\\0 & 1 & 0 & 0 & 3\\0 & 0 & 1 & 0 & -5\\0 & 0 & 0 & 1 & 1\end{matrix}\right] $$最后一列是解,即三次多项式的系数。所求三次多项式为 \begin{align} y = 4 + 3x - 5x^2 + x^3 \end{align}
import sympy as sy
def pl(m):
x= '$$'+sy.latex(m)+'$$'
print(x)
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
%matplotlib inline
A = sy.Matrix([[3, 6, 2, -13], [1, 2, 1, -5], [-5, -10, -2, 19]]);A
print(sy.latex(A))
\left[\begin{matrix}3 & 6 & 2 & -13\\1 & 2 & 1 & -5\\-5 & -10 & -2 & 19\end{matrix}\right]
A_rref = A.rref(); A_rref
(Matrix([ [1, 2, 0, -3], [0, 0, 1, -2], [0, 0, 0, 0]]), (0, 2))
a, b, c = sy.symbols('a, b, c', real = True)
A = sy.Matrix([[1, 2, -3, a], [4, -1, 8, b], [2, -6, -4, c]]); A
A_rref = A.rref(); A_rref
(Matrix([ [1, 0, 0, 2*a/7 + b/7 + c/14], [0, 1, 0, 16*a/91 + b/91 - 10*c/91], [0, 0, 1, -11*a/91 + 5*b/91 - 9*c/182]]), (0, 1, 2))
A_rref[0]
A = sy.Matrix([[1, 1, 1, 1, 3], [1, 2, 4, 8, -2], [1, 3, 9, 27, -5], [1, 4, 16, 64, 0]]); A
A_rref = A.rref(); A_rref[0]
A = sy.Matrix([[1, 1, 1, 1, 3], [1, 2, 4, 8, -2], [1, 3, 9, 27, -5], [1, 4, 16, 64, 0]])
A_rref = A.rref()
A_rref = np.array(A_rref[0])
poly_coef = A_rref.astype(float)[:,-1]
x = np.linspace(-5, 5, 40)
y = poly_coef[0] + poly_coef[1]*x + poly_coef[2]*x**2 + poly_coef[3]*x**3.5
fig, ax = plt.subplots(figsize = (7, 5))
ax.plot(x, y, lw = 3, color ='red')
ax.scatter([1, 2, 3, 4], [3, -2, -5, 0], s = 100, color = 'blue', zorder = 3)
ax.grid()
ax.set_xlim([0, 5])
ax.set_ylim([-10, 10])
ax.text(1, 3.5, '$(1, 3)$', fontsize = 15)
ax.text(1.5, -2.5, '$(2, -2)$', fontsize = 15)
ax.text(2.7, -4, '$(3, -5.5)$', fontsize = 15)
ax.text(4.1, 0, '$(4, .5)$', fontsize = 15)
plt.savefig('images/lin0202.png')
<ipython-input-47-db7151f4f30a>:6: RuntimeWarning: invalid value encountered in power y = poly_coef[0] + poly_coef[1]*x + poly_coef[2]*x**2 + poly_coef[3]*x**3.5